package com.iflysse.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {



    //有效期
    private static final Integer date=365;

    //密钥
    private static final String key="iflytek";

    /**
     * 根据用户编号和角色生成token
     * @param userId
     * @param role
     * @return
     */
    public static String createToken(String userId,String role) throws Exception{
        Calendar c= Calendar.getInstance();
        c.add(Calendar.DATE,date);
        Date date=c.getTime();

        Map<String,Object> map=new HashMap<String,Object>();
        map.put("alg","HS256");
        map.put("typ","JWT");

        String token=  JWT.create().withHeader(map)//设置头的信息
                .withClaim("userId",userId)
                .withClaim("role",role)
                .withSubject("生成token")
                .withIssuedAt(c.getTime())
                .withExpiresAt(date)
                .sign(Algorithm.HMAC256(key));
        return token;
    }

    /**
     * 根据token信息反解析回来成Map
     * @param token
     * @return
     */
    public static Map<String, Claim>parseToken(String token){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Map<String, Claim> map = decodedJWT.getClaims();
            return map;
        }catch (Exception e){
            System.out.println("token信息有误，token值为："+token);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String token=  createToken("zhangsan","666666");
        System.out.println(token);
        Map<String,Claim>map= parseToken(token);
        String userId= map.get("userId").asString();
        String role= map.get("role").asString();
        System.out.println(map);
        System.out.println("userId="+userId+",role="+role);
    }


}
